(İÇ?) JOIN açgözlü ile yardım

2 Cevap php

Ben sorun bir sorgu oluşturma yaşıyorum. Ben 3 farklı sorgularda istediğimi yapabilirim.

SELECT id FROM table1 WHERE url LIKE '%/$downloadfile'
put that in $url_id
SELECT item_id FROM table2 WHERE rel_id = '$url_id'"
put that in $item_id
SELECT rel_id FROM table2 WHERE rel_id = '$item_id' AND field_id = '42'"
put that in $user_id

Ama üzerinde örnekler okuma katılır ve iç ben daha şık bir yolu olduğunu düşünüyorum katıldı. Ben daha iyi bir sorgu yazma etrafında beynimi sarın olamaz (ama istiyorum) Ben gitmeli nasıl tanımlayabiliriz:

table1 fields: id, url

table2 fields item_id, rel_id, field_id

I know the last part of table1.url (LIKE '%/$filename') with that I select table1.id. table1.id is equal to one entry in table2.rel_id. So get that and select the table2.item_id. In table2 there is another entry which has the same table2.item_id and it will have a table2.field_id = '42' And finally the value I need is the table2.rel_id where the table2.field_id was 42. I will fetch that value and put it in $user_id

Bu kullanarak bir sorgu ile yapılabilir katıldı / iç birleşimler?

2 Cevap

Tabii, böyle bir şey olmalı:

SELECT t2_second.rel_id
FROM table1 t1
INNER JOIN table2 t2_first ON t1.id = t2_first.rel_id
INNER JOIN table2 t2_second ON t2_second.rel_id = t1_first.item_it
WHERE 
   t1.url = '%/:filename' AND
   t2_second.field_id = 42

: Her t2_second.rel_id sadece bir kez döndürülür ve böylece bile ayrı atmak olabilir

SELECT DISTINCT [...]

Bunu gerek olmayabilir, ancak, eğer t2_second.field_id = 42 sadece her t2_second.rel_id için bir satır dönmek için sorgu sınırlar

Benim için çalışıyor, bu sorgu, Ignacio cevabı için küçük bir değişiklik yaptık:

SELECT url, second.rel_id AS user_id
FROM table1
INNER JOIN table2 AS first
  ON table1.id=first.rel_id
INNER JOIN table2 AS second
  ON first.item_id=second.item_id
WHERE second.field_id='42'
  AND table1.url LIKE '%/:downloadfile'