2017-07-31 66 views
0

我有一個表articlesidname,表companyidname和數據透視表(article_company)與idarticle_idcompany_idpriceMySQL的選擇只有一些在數據透視錶行和所有行表

我想將一篇文章與一家公司聯繫起來,所以我需要一份關於所有產品的請求,並且他們是否與這家公司有關聯。

我嘗試此查詢:

SELECT article_id, name, price AS price, 1 AS associated FROM articles JOIN article_company ON articles.id = article_company.article_id WHERE company_id = 26 UNION SELECT id AS article_id, name, NULL AS price, 0 AS associated FROM articles GROUP BY article_id

但不幸的是我從文章表和company_article兩篇文章。

如果它不是很清楚,我想擁有所有的文章行,但是如果文章位於company_article中,我想要該表中的行。

編輯:數據表: - 文章:

+----+--------------+ 
| id | name   | 
+----+--------------+ 
| 1 | Aez   | 
| 2 | aze   | 
| 3 | za   | 
| 4 | azee   | 
| 5 | article test | 
| 6 | test 2  | 
| 7 | Test 3  | 
+----+--------------+ 

-company_article:

+------------+------------+-------+ 
| article_id | company_id | price | 
+------------+------------+-------+ 
|   5 |   26 | 54.00 | 
|   3 |   26 | 8.90 | 
+------------+------------+-------+ 

我有什麼和行我想:

+------------+--------------+-------+------------+ 
| article_id | name   | price | associated | 
+------------+--------------+-------+------------+ 
|   5 | article test | 54.00 |   1 | < 
|   3 | za   | 8.90 |   1 | < 
|   1 | Aez   | NULL |   0 | < 
|   2 | aze   | NULL |   0 | < 
|   3 | za   | NULL |   0 | 
|   4 | azee   | NULL |   0 | < 
|   5 | article test | NULL |   0 | 
|   6 | test 2  | NULL |   0 | < 
|   7 | Test 3  | NULL |   0 | < 
+------------+--------------+-------+------------+ 
+3

表結構,樣本數據,預期結果只是增加 – Matt

+0

表格文章和article_company以及查詢的行 –

回答

0

好了,所以我覺得自己這是我提出的要求:

SELECT article_id as id, name, price 
    res.associated as associated, created_at 
    FROM (
    SELECT 
     article_id, name, price 
     1 AS associated, created_at 
    FROM articles 
    JOIN article_company ON articles.id = article_company.article_id 
    WHERE company_id = $id 
    UNION ALL 
    SELECT 
     id AS article_id, name, null as price 
     0 AS associated, created_at 
    FROM articles) AS res 
GROUP BY article_id 
ORDER BY associated DESC 
相關問題