1

我希望有人能够指出我正确的方向。

我有一个 COUNTRY 表,其中包含一个主 ID 和国家名称(例如法国)

我有第二个表 PAYMETHODS_COUNTRIES,其中包含主 ID、付款方式 ID(例如 4)和国家/地区 ID

我正在尝试输出每种付款方式的复选框列表,以控制哪些国家(或哪些国家的用户)可以访问这些本地付款方式。

我的复选框列表工作正常,表单的处理也正常。最后剩下的事情是输出带有选定国家的国家复选框列表(例如,这种付款方式在法国和德国可用)显示为 CHECKED。

所以我想做的是输出所有国家的完整列表

SELECT id, name FROM country ORDER BY id ASC

然后包括类似这样的 PAYMETHODS_COUNTRIES 表(当然不工作)

SELECT country.id AS countryid,
country.name AS countryname,
paymethods_countries.id AS methodid
FROM country LEFT JOIN `paymethods_countries` 
ON country.id = paymethods_countries.country
WHERE paymethods_countries.paymethod = 10

此示例查询仅显示实际在 PAYMETHODS_COUNTRIES 中有记录的行,而不是我所追求的。

我所希望的是 country.id + country.name 的完整列表,其中包含最后一个字段(PAYMETHODS_COUNTRIES 表的 ID) - 在没有链接的情况下应该为 null。这样我应该能够检查 null 或其他,并为这些行输出 CHECKED。

希望这是有道理的——或者如果有人知道更好的方法来实现我正在做的事情,你的想法将不胜感激。

4

2 回答 2

2

由于您的 WHERE 子句,它只会返回在 PAYMETHODS_COUNTRIES 中有记录的行,因为您说 paymethod 必须 = 10。添加一个 OR 让它也为空:

SELECT country.id AS countryid,
   country.name AS countryname,
   paymethods_countries.id AS methodid
FROM country 
LEFT JOIN `paymethods_countries` 
   ON country.id = paymethods_countries.country
WHERE paymethods_countries.paymethod = 10
   OR paymethods_countries.paymethod IS NULL
于 2012-11-12T04:35:28.453 回答
2

While the other answer here will produce the desired result, semantically it is more correct to move the condition from the WHERE clause to the ON clause:

SELECT country.id AS countryid,
    country.name AS countryname,
    paymethods_countries.id AS methodid
FROM country 
LEFT JOIN `paymethods_countries` 
   ON country.id = paymethods_countries.country and paymethods_countries.paymethod = 10

This eliminates the need to add the extra OR condition in the WHERE clause.

于 2012-11-12T04:39:17.400 回答