![](/img/trans.png)
[英]In MySQL how do I count fields on a table by value in an inner join, then left join those results to a SELECT?
[英]How to do a conditional mysql left join based on table in the actual fields using query builder
在設置產品時,我可以選擇將其可用性限制在客戶的國家、地區和城市。 基於此,我只向系統中符合此條件的相關客戶展示產品。
在某些情況下,我只想將產品設置為國家/地區而忽略城市,我想知道如何最好地編寫此查詢。
在我看來,我有兩個選擇。
產品:
+---------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| uuid | binary(16) | NO | UNI | NULL | |
+---------------------+------------------+------+-----+---------+----------------+
多對多連接到位置
+------------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+-------+
| product_id | int(10) unsigned | NO | PRI | NULL | |
| meta_location_id | int(11) | NO | PRI | NULL | |
+------------------+------------------+------+-----+---------+-------+
地點
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| iso | varchar(50) | YES | | NULL | |
+-------------+---------------+------+-----+---------+----------------+
查詢生成器代碼
$qb = $this->repository->createQueryBuilder('product');
$qb->orderBy('product.id', 'ASC');
//If we are limiting by country
if (isset($options['country']) and null !== $options['country']) {
$qb->andWhere('product.country = :country')
->setParameter('country', $options['country']);
}
地區/城市:
區域選項是客戶的當前區域,無論如何都會發送,我無法控制它。 由於我在產品表中搜索,我需要檢查產品區域是否存在。 如果是這樣,那么我必須將其限制在現有區域,否則忽略它。
CURRENT QUERY:使用此查詢,如果區域不匹配,則不會列出產品。 我想將其更改為僅適用於產品表中存在數據的情況。
if (isset($options['region']) and null !== $options['region']) {
$qb->leftJoin('product.regions', 'region');
->andWhere(($qb->expr()->in('region', [$options['region']])));
}
我猜我需要一些類似的東西
$qb->add('select', 'CASE WHEN region.id IS NOT NULL then do some query...
任何想法,將不勝感激!
這就是我解決這個問題的方法。
而不是做一些復雜的事情,比如試圖弄清楚一個連接是否包含數據。 我只是在我們的元位置表中創建了一個虛擬行。
我們的連接現在看起來像這樣:
if (isset($options['region']) and null !== $options['region']) {
$qb->leftJoin('product.regions', 'region');
->andWhere(($qb->expr()->in('region', [12345, $options['region']])));
}
其中 12345 是虛擬行的 ID。
設置產品時,在表單下拉菜單中,我有一個名為“任何”的項目,這意味着客戶居住在哪個地區並不重要,就像任何地區一樣。
因此,如果選擇了任何連接,則現在連接將有效,否則,如果該區域與實際區域匹配,則它也可以工作。
好吧,我們有它,通常最簡單的解決方案是最好的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.