Mysql
 sql >> Baza danych >  >> RDS >> Mysql

mysql wartości zapytania dołączającego do tabeli 2

Jest wiele sposobów na rozwiązanie tego; najprostszym byłoby prawdopodobnie użycie kilku exists klauzul lub dołącz do attributes tabeli dwa razy, ale możesz również użyć group by i having klauzule, aby osiągnąć ten sam wynik:

-- option 1: using multiple exists clauses
select p.id, p.productname
from Products p
where exists (select 1 from Attributes a where p.ID = a.ProductID and a.AttributeID = 3)
  and exists (select 1 from Attributes a where p.ID = a.ProductID and a.AttributeID = 4);

-- option 2: using multiple joins
select p.id, p.productname
from Products p
join Attributes a3 on p.ID = a3.ProductID
join Attributes a4 on p.ID = a4.ProductID
where a3.AttributeID = 3
  and a4.AttributeID = 4;

-- option 3: using aggregate and having
select p.id, p.productname
from Products p
join Attributes a on p.ID = a.ProductID
group by p.id, p.productname
having sum(case when a.AttributeID = 3 then 1 else 0 end) > 0
   and sum(case when a.AttributeID = 4 then 1 else 0 end) > 0;

-- option 4: using having and count
select p.id, p.productname
from Products p
join Attributes a on p.ID = a.ProductID
where a.AttributeID in (3,4)
group by p.id, p.productname
having count(distinct a.attributeid) = 2;

Który sposób jest dla Ciebie najlepszy, prawdopodobnie zależy od tego, jakiego wyniku potrzebujesz, indeksów i tak dalej.

Przykładowe skrzypce SQL.




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Instalacja Neo4j

  2. Jak utworzyć zadanie Cron do tworzenia kopii zapasowych MySQL i FTP na moim serwerze kopii zapasowych?

  3. Czy istnieje sposób na wsteczne tworzenie UUID opartego na czasie/węźle w PHP?

  4. Jetty 7 + konfiguracja MySQL [java.lang.ClassNotFoundException:org.mortbay.jetty.webapp.WebAppContext]

  5. Wyjątki MySQLdb w Pythonie