Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL UNION query Syntax issue
    primarykey
    data
    text
    <p>Let's say that I want to get records from 2 different tables (which have the same structure) by using UNION.</p> <p>The query is something like this :</p> <pre><code>SELECT * FROM ( (SELECT `a1`.`title`, `a1`.`updated_date`, `a1`.`plain_description`, `a1`.`thumb`, `a1`.`link`, `c1`.`alias` as category_alias FROM (`articles1` as a1) LEFT JOIN `article_categories1` as c1 ON `c1`.`id`=`a1`.`category_id` WHERE `a1`.`visible` = 1 AND `c1`.`alias` = 'category-alias' AND `c1`.`visible` = 1) UNION (SELECT `a2`.`title`, `a2`.`updated_date`, `a2`.`plain_description`, `a2`.`thumb`, `a2`.`link`, `c2`.`alias` as category_alias FROM (`articles2` as a2) LEFT JOIN `article_categories2` as c2 ON `c2`.`id`=`a2`.`category_id` WHERE `a2`.`visible` = 1 AND `c2`.`visible` = 1) ) as t ORDER BY t.updated_date DESC LIMIT 0, 5 </code></pre> <p>When I execute the query it shows :</p> <pre><code>[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN `article_categories2` as c2 ON `c2`.`id`=`a2`.`category_id` </code></pre> <p>What was wrong here?</p> <pre><code>**`UPDATED`** </code></pre> <p>Remove parentheses in sub queries solved the problem. Just one more thing, how could I add a field to each record that would tell me which table it belong to. Assume that I want to have something like this:</p> <pre><code>id | title | link | table ----------------------------------------------------- 1 | Title 1 | somelink.html | articles1 2 | Title 2 | link2 .html | articles2 3 | Title 3 | link3 .html | articles1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload