Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL group_concat+;子查询或子字符串索引_Mysql_Sql - Fatal编程技术网

MySQL group_concat+;子查询或子字符串索引

MySQL group_concat+;子查询或子字符串索引,mysql,sql,Mysql,Sql,我有两张桌子: - tb_shops shop_id PK shop_name - tb_products product_id PL product_name shop_id FK 我需要列出如下内容: shop_name | product01,product02,product03,product04 shop_name2 | product05,product06,product07,prodcut08 但这些产品需要有一个限制,每家商店4 我试过这些问题: 带子查询的Fist

我有两张桌子:

- tb_shops
shop_id PK
shop_name

- tb_products

product_id PL
product_name
shop_id FK
我需要列出如下内容:

shop_name | product01,product02,product03,product04
shop_name2 | product05,product06,product07,prodcut08
但这些产品需要有一个限制,每家商店4

我试过这些问题:

带子查询的Fist

select SQL_NO_CACHE a.shop_id,
        a.shop_name,
        count(b.product_id) as ptotal,
        (select group_concat(_b.product_name separator ',') from tb_shops _a left join tb_products _b using(shop_id) where _a.shop_id=a.shop_id group by _a.shop_id limit 4) as products 
from tb_shops a 
left join tb_products b on a.shop_id=b.shop_id 
group by a.shop_id
order by a.shop_name asc
第二个是子串_索引

select SQL_NO_CACHE a.shop_id,
        a.shop_name,
        count(distinct b.product_id) as ptotal,
        substring_index(group_concat(distinct c.product_name separator ','),',',4) as products 
from tb_shops a 
left join tb_products b on a.shop_id=b.shop_id 
left join tb_products c on a.shop_id=c.shop_id 
group by a.shop_id
order by a.shop_name asc

这些哪个更好?或者有人知道更好的解决方案?

您真的需要子查询吗?如果只在主查询中执行group_concat,会发生什么情况?它将返回4种以上的产品我只需要列出每个购物者的4种产品。对不起,我没有仔细阅读。但是我想当使用MySQL时,join版本是更好的选择。@jarlh,我不知道,因为想象一个例子,如果shop01有200个产品,所有这些产品都会出现在这个查询中,那么它将被一个字符串函数拆分为4个项目