sql的子查询语法错误

时间:2016-05-20 10:01:57

标签: mysql

您好我正在尝试从PHP和MySQL中的两个表(productsissues)中获取数据。

issues表中,有一列status,它有四个不同的值。我想要做的是在每个产品的四个不同列中显示status值,如下所示:

S.No      Product Name    Status Val1    Status Val2   Status Val2 Status Val4

我在下面使用以下查询

SELECT i.product_id, i.status, COUNT( * ) AS count FROM issues i 
INNER JOIN products p ON i.product_id = p.id 
GROUP BY `product_id`

3 个答案:

答案 0 :(得分:1)

如果您只想显示产品的所有已分配状态,则不需要子查询(如果存在有限数量的状态)

如果您的表结构与此类似:

CREATE TABLE products
    (`id` int, `name` varchar(4))
;
CREATE TABLE issues
    (`product_id` int, `status` varchar(2))
;

然后你可以使用这个简单的查询

SELECT p.id, p.name, i1.status AS 'S1', i2.status AS 'S2', i3.status AS 'S3', i4.status AS 'S4'
FROM products p
LEFT JOIN issues i1 ON p.id=i1.product_id AND i1.status = "S1"
LEFT JOIN issues i2 ON p.id=i2.product_id AND i2.status = "S2"
LEFT JOIN issues i3 ON p.id=i3.product_id AND i3.status = "S3"
LEFT JOIN issues i4 ON p.id=i4.product_id AND i4.status = "S4"

这是sqlFiddle

答案 1 :(得分:1)

SELECT p.name,

(从状态= val1和product_id = p.id的问题中选择计数(*))作为状态Val1,

(从status = val2 AND product_id = p.id的问题中选择count(*))作为Status Val2,

(从状态= val3和product_id = p.id的问题中选择计数(*))作为状态Val3,

(从状态= val4 AND product_id = p.id的问题中选择计数(*))作为状态Val4

FROM问题INNER JOIN产品p

ON i.product_id = p.id

GROUP BY product_id

答案 2 :(得分:0)

谢谢你们,我已经解决了它

SELECT p.name,
(select count(*) from issues where status=val1 AND product_id=p.id) as Status Val1,
(select count(*) from issues where status=val2 AND product_id=p.id) as Status Val2,
(select count(*) from issues where status=val3 AND product_id=p.id) as Status Val3,
(select count(*) from issues where status=val4 AND product_id=p.id) as Status Val4
FROM issues i INNER JOIN products p 
ON i.product_id = p.id 
where p.branch_id = 1
GROUP BY product_id