簡體   English   中英

MySQL僅在數據透視表中選擇一些行,並在表中選擇所有行

[英]MySQL Select only some rows in pivot table and all rows in table

我有一個表articlesidname ,表companyid和一個name和數據透視表( article_company有) idarticle_idcompany_idprice

我想將某條文章與一家公司相關聯,因此我需要所有產品以及它們是否與該公司相關聯的要求。

我試過這個查詢:

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

但不幸的是,我同時擁有articles table和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 | <
+------------+--------------+-------+------------+

嘗試這樣的事情:

SELECT * FROM articles a LEFT OUTER JOIN company_article ca ON a.id = 
ca.article_id;

這是左外部聯接的說明: http : //docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj18922.html

好吧,我發現自己這是我提出的要求:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM