简体   繁体   English

如果第二个表中至少有4条记录,则从两个表中选择记录

[英]Select records from two tables if atleast 4 records in second table

I have 2 tables and i want to fetch data based on below condition: 我有2个表,我想根据以下条件获取数据:

  • Table1 has multiple product records. 表1具有多个产品记录。
  • Table2 contains various Size option for products and can not have more or less than 4 rows. Table2包含产品的各种Size选项,并且不能多于或少于4行。

Now, i want to fetch those products which do not have entry or do not have exact 4 entries. 现在,我想获取那些没有条目或没有确切4条条目的产品。

Table Structure is as below: 表结构如下:

Table1 表格1

id   name  color  price   instock
----------------------------------
 1   rice   white  1200    1
 2   shoe   brown  2500    1
 3   belt   red    5200    1

Table2 表2

  id   size   pid
 -----------------
  1     5     1
  2     10    1
  3     4     1 
  4     15    1
  5     7     2

Now Query shall fetch product with ID 2 and 3 as they have records less than 4 and no record resp. 现在,查询将获取ID为2和3的产品,因为它们的记录少于4个且没有记录。

I was using below query to fetch products which have no records in Table2 我正在使用下面的查询来获取在Table2没有记录的产品

SELECT p.* FROM `Table1` p LEFT JOIN `Table2` t ON p.id = t.pid  WHERE 
t.pid IS NULL
SELECT p.id, p.name, p.color, p.price, p.instock, count(t.*) 
FROM `Table1` p 
LEFT JOIN `Table2` t 
ON p.id = t.pid  
GROUP BY p.id, p.name, p.color, p.price, p.instock
HAVING count(t.*) < 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM