2017-07-31 118 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