subquery returns more than 1 row ? sulution ?
SELECT `t_files`.*, `t_users`.`username`,
(SELECT CONCAT(b.first_name, " ", b.last_name)
FROM t_files AS a
JOIN t_users as b
ON b.id = a.user_id
) as upload_by
FROM `t_files`
LEFT JOIN `t_files_permission`
ON `t_files_permission`.`id_files` = `t_files`.`file_id`
LEFT JOIN `t_users`
ON `t_users`.`id` = `t_files_permission`.`id_users`
WHERE `t_files`.`company_id` = '1'
AND `t_files_permission`.`id_users` = '59'
AND `is_deleted` =0
Add the condition in your sub query like below
SELECT t_files.*, t_users.username,
(SELECT CONCAT(b.first_name, " ", b.last_name)
FROM t_files AS a
JOIN t_users AS b ON b.id = a.user_id
WHERE a.id_users` = '59'
) as upload_by
FROM t_files
LEFT JOIN t_files_permission ON t_files_permission.id_files = t_files.file_id
LEFT JOIN t_users ON t_users.id = t_files_permission.id_users
WHERE t_files.company_id = '1' AND t_files_permission.id_users = '59' AND is_deleted =0
try this way
SELECT `t_files`.*, `t_users`.`username`,
(select CONCAT(b.first_name, " ", b.last_name)
from t_files as a
join t_users as b on b.id = a.user_id
where t.files.id=a.id) as upload_by
FROM `t_files` as
LEFT JOIN `t_files_permission` ON `t_files_permission`.`id_files` = `t_files`.`file_id`
LEFT JOIN `t_users` ON `t_users`.`id` = `t_files_permission`.`id_users`
WHERE `t_files`.`company_id` = '1' AND `t_files_permission`.`id_users` = '59' AND `is_deleted` =0
I think you don't need sub query. You can use join to resolve stuff.
Related
I'm currently stuck here and don't know what to do next since I can't use the tv_main alias into the 2 level deep subquery. Here's my code (I commented the part that have a problem). Any help will be appreciated. Thanks.
SELECT tv_main.id,
tv_main.vesselName,
(
SELECT SUM(t_statCtr.status = 'EX CREW')
FROM
(
(
SELECT tpi_stat.id,
tvv.vesselName,
lastname,
firstname,
middlename,
IF(tpi_stat.returningCrew = 1, 'NEW HIRE',
IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE')
)
AS status
FROM tbl_contracts AS tc_stat
LEFT JOIN tbl_personnel_info AS tpi_stat
ON tpi_stat.id = tc_stat.personnel_id
LEFT JOIN tbl_contracts AS tc_ctr
ON tpi_stat.id = tc_ctr.personnel_id
LEFT JOIN tbl_vessels AS tvv
ON tvv.id = tpi_stat.lastJoinedVsl
WHERE
tpi_stat.emp_status = 'ON-BOARD'
AND tc_stat.status = 'ACTIVE'
AND tvv.id = tv_main.id --This line have an error, (Unknown Column tv_main.id in where clause)
GROUP BY tc_stat.personnel_id
) AS t_statCtr
)
) AS ex_crew,
NULL AS new_hire
FROM tbl_vessels AS tv_main -- I need this one to use inside the subquery
LEFT JOIN tbl_personnel_info AS tpi
ON tv_main.id = tpi.lastJoinedVsl
LEFT JOIN tbl_contracts AS tc
ON tpi.id = tc.personnel_id
WHERE
tpi_stat.emp_status = 'ON-BOARD'
AND tc_stat.status = 'ACTIVE'
GROUP BY tv_main.vesselName
I finally solve it. I didn't know that mysql only allow correlation of 1 deep level.
SELECT tv_main.vesselName,
SUM(t_dummy.statusx = 'EX CREW') AS ex_crew,
SUM(t_dummy.statusx = 'NEW HIRE') AS new_hire
FROM tbl_vessels AS tv_main
LEFT JOIN tbl_personnel_info AS tpi_main
ON tpi_main.lastJoinedVsl = tv_main.id
LEFT JOIN tbl_contracts AS tc_main
ON tc_main.personnel_id = tpi_main.id
LEFT JOIN
(
SELECT tvv.id,
tpi_stat.id AS tpiid,
IF(tpi_stat.returningCrew = 1, 'NEW HIRE',
IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE')
)
AS statusx
FROM tbl_contracts AS tc_stat
LEFT JOIN tbl_personnel_info AS tpi_stat
ON tpi_stat.id = tc_stat.personnel_id
LEFT JOIN tbl_contracts AS tc_ctr
ON tpi_stat.id = tc_ctr.personnel_id
LEFT JOIN tbl_vessels AS tvv
ON tvv.id = tpi_stat.lastJoinedVsl
GROUP BY tc_stat.personnel_id
) AS t_dummy
ON tpi_main.id = t_dummy.tpiid
WHERE
tpi_main.emp_status = 'ON-BOARD'
AND tc_main.status = 'ACTIVE'
AND t_dummy.id = tv_main.id
GROUP BY tv_main.vesselName;
mysql query:
`SELECT IFNULL(party.`user_id`, 0) as isparticipant, a.`id`, a.`created`,` `a.`lastreplied`,`
a.`type`, b.`created_by`, b.`message`, c.`isread`
FROM `jos_social_conversations` AS `a`
LEFT JOIN `jos_social_conversations_participants` as party on a.id = party.conversation_id
and party.user_id = '602'
INNER JOIN `jos_social_conversations_message` AS `b` ON
`a`.`id` = `b`.`conversation_id`
INNER JOIN `jos_social_conversations_message_maps` AS `c`
ON `c`.`message_id` = `b`.`id` and c.`conversation_id` = b.`conversation_id`
INNER JOIN
(select cm.`conversation_id`, max(cm.`message_id`) as `message_id` from
`jos_social_conversations_message_maps` as cm
inner join `jos_social_conversations_message` as bm
on cm.`message_id` = bm.`id`
LEFT JOIN `jos_social_block_users` AS `bus` ON `bm`.`created_by` = `bus`.`user_id`
AND `bus`.`target_id` = '602'
WHERE `cm`.`user_id` = '602' AND(SELECT count(isread) AS newMsg
FROM jos_social_conversations_message_maps as maps WHERE a.id = maps.conversation_id AND
maps.isread = 0 AND maps.user_id = '602') AND `cm`.`state` = '1' and `bus`.`id` IS NULL
group by cm.`conversation_id`) as x ON c.`message_id` = x.`message_id`
LEFT JOIN `jos_social_block_users`
as bus ON a.`created_by` = bus.`user_id` AND bus.`target_id` = '602'
WHERE `c`.`user_id` = '602'
AND bus.`id` IS NULL AND `c`.`state` = '1'
AND this gives error like:
1054 - Unknown column 'a.id' in 'where clause'
subquery from above query as below:
AND(SELECT count(isread) AS newMsg FROM jos_social_conversations_message_maps WHERE conversation_id = 3 AND isread = 0 AND user_id = '602')
Current output:
Expected output:
There should be another column called 'newMsg' displaying total count of 'isread' column which has '0' as value for each id..
Here's my formatted version:
SELECT IFNULL(party.`user_id`, 0) as isparticipant, a.`id`, a.`created`, a.`lastreplied`, a.`type`, b.`created_by`, b.`message`, c.`isread`
FROM `jos_social_conversations` AS `a`
LEFT JOIN `jos_social_conversations_participants` as party on a.id = party.conversation_id and party.user_id = '602'
INNER JOIN `jos_social_conversations_message` AS `b` ON `a`.`id` = `b`.`conversation_id`
INNER JOIN `jos_social_conversations_message_maps` AS `c` ON `c`.`message_id` = `b`.`id` and c.`conversation_id` = b.`conversation_id`
INNER JOIN (select cm.`conversation_id`, max(cm.`message_id`) as `message_id`
from `jos_social_conversations_message_maps` as cm
inner join `jos_social_conversations_message` as bm on cm.`message_id` = bm.`id`
LEFT JOIN `jos_social_block_users` AS `bus` ON `bm`.`created_by` = `bus`.`user_id` AND `bus`.`target_id` = '602'
WHERE `cm`.`user_id` = '602' AND(SELECT count(isread) AS newMsg
FROM jos_social_conversations_message_maps
WHERE conversation_id = 3 AND isread = 0 AND user_id = '602'
)
AND `cm`.`state` = '1'
and `bus`.`id` IS NULL
group by cm.`conversation_id`
) as x ON c.`message_id` = x.`message_id`
LEFT JOIN `jos_social_block_users` as bus ON a.`created_by` = bus.`user_id` AND bus.`target_id` = '602'
WHERE `c`.`user_id` = '602'
AND bus.`id` IS NULL AND `c`.`state` = '1'
Your subquery is part of the WHERE clause, so it will not return another column. Perhaps you are lookig for something like this:
SELECT IFNULL(party.`user_id`, 0) as isparticipant, a.`id`, a.`created`, a.`lastreplied`, a.`type`, b.`created_by`, b.`message`, c.`isread`,
(SELECT count(isread)
FROM jos_social_conversations_message_maps
WHERE conversation_id = 3 AND isread = 0 AND user_id = '602'
) AS newMsg
FROM `jos_social_conversations` AS `a`
{remainder removed for brevity}
It shouldn't join on tbi2 if tbi1 finds a result, but it retrieving results from both tables.
The idea of this is to join on the item table but if there isn't an exact match, fallback to joining on '*'
(This is the same SQL statement as a previous question, but a different attempt... again.)
SELECT
COALESCE(tbi1.id,tbi2.id,tbi3.id,tbi4.id,tbi5.id,tbi6.id) AS id
,COALESCE(tbi1.cost,tbi2.cost,tbi3.cost,tbi4.cost,tbi5.cost,tbi6.cost) AS cost
,COALESCE(tbi1.price,tbi2.price,tbi3.price,tbi4.price,tbi5.price,tbi6.price) AS price
,COALESCE(tbi1.itemNumber,tbi2.itemNumber,tbi3.itemNumber,tbi4.itemNumber,tbi5.itemNumber,tbi6.itemNumber) AS itemNumber
,COUNT(COALESCE(tbi1.id,tbi2.id,tbi3.id,tbi4.id,tbi5.id,tbi6.id)) AS quantityToAdd
,tbl_equipment.id AS equipId
,tbl_equipment.partNum
,tbl_equipment.nolinks
,tbl_addedItemCustomerPrices.customerprice AS specialPrice
,tbl_testTypes.isInspt
,tbl_testTypes.isRecharge
,tbl_testTypes.isRecharagable
,tbl_tests.nextDate AS theNextDate
FROM
tbl_tests
INNER JOIN tbl_equipment ON tbl_equipment.id = tbl_tests.equipmentId
INNER JOIN tbl_model ON tbl_model.id = tbl_equipment.model
INNER JOIN tbl_testTypes ON tbl_testTypes.id = tbl_tests.testTypeId
LEFT JOIN tbl_items AS tbi1 ON tbi1.size = tbl_model.size AND tbi1.service = tbl_testTypes.name
LEFT JOIN tbl_items AS tbi2 ON tbi2.size = '*' AND tbi2.service = tbl_testTypes.name AND tbi1.id IS NULL
LEFT JOIN tbl_items AS tbi3 ON tbi3.type = tbl_model.type AND tbi3.service = tbl_testTypes.name AND tbi2.id IS NULL
LEFT JOIN tbl_items AS tbi4 ON tbi4.type = '*' AND tbi4.service = tbl_testTypes.name AND tbi3.id IS NULL
LEFT JOIN tbl_items AS tbi5 ON tbi5.category = tbl_model.category AND tbi5.service = tbl_testTypes.name AND tbi4.id IS NULL
LEFT JOIN tbl_items AS tbi6 ON tbi6.category = '*' AND tbi6.service = tbl_testTypes.name AND tbi5.id IS NULL
LEFT JOIN tbl_addedItemCustomerPrices ON COALESCE(tbi1.id,tbi2.id,tbi3.id,tbi4.id,tbi5.id,tbi6.id) = tbl_addedItemCustomerPrices.itemId AND tbl_addedItemCustomerPrices.customerid = $currentSite
WHERE
((nextDate >= '$startDate' AND nextDate <= '$endDate' ) OR tbl_testTypes.isRecharge = 'true')
{$monthEndQuery}
AND tbl_equipment.site = $currentSite
GROUP BY COALESCE(tbi1.id,tbi2.id,tbi3.id,tbi4.id,tbi5.id,tbi6.id)
ORDER BY tbl_equipment.id, isRecharagable DESC
Hi I have run into a dilemma, I am doing this query:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, pr.promo_name, pr.add_value_text, c.contract_id, c.cmeal_plan, c.cmin_markup, c.civa, c.tax_include, c.hotel_id, hi.hname, hi.hstars, im.image_file, pl.plan_name, ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi ON hi.hotel_id = c.hotel_id AND hi.destination_id = '6460'
INNER JOIN images AS im ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl ON pl.plan_code = c.cmeal_plan AND pl.lang = '1'
INNER JOIN hotel_categories AS hc ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca ON ca.category_code = hc.category_code AND ca.lang = '1'
LEFT JOIN
(SELECT
r.hotel_id, AVG(r.double) AS price
FROM
rates AS r ) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr ON pr.hotel_id = hi.hotel_id AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 AND pr.book_start <= '2012-11-01' AND pr.book_end >= '2012-11-02' AND travel_start <= '2012-11-23' AND travel_end >= '2012-11-30' AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01' AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id
I am getting all the desired results except for the sub select query.. each hotel has a price but it is only giving me back one result and the rest are all null. Is there an error in my query? If any additional information is needed please let me know and thank you in advance for any help!
You are missing the GROUP BY in your subquery, so MySQL will only return one-value. If you want all hotel_id's then you need to GROUP BY that field:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories,
pr.promo_name,
pr.add_value_text,
c.contract_id,
c.cmeal_plan,
c.cmin_markup,
c.civa,
c.tax_include,
c.hotel_id,
hi.hname,
hi.hstars,
im.image_file,
pl.plan_name,
ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi
ON hi.hotel_id = c.hotel_id
AND hi.destination_id = '6460'
INNER JOIN images AS im
ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl
ON pl.plan_code = c.cmeal_plan
AND pl.lang = '1'
INNER JOIN hotel_categories AS hc
ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca
ON ca.category_code = hc.category_code
AND ca.lang = '1'
LEFT JOIN
(
SELECT r.hotel_id, AVG(r.double) AS price
FROM rates AS r
GROUP BY r.hotel_id <-- add a GROUP BY hotel_id then you will get avg() for each hotel
) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr
ON pr.hotel_id = hi.hotel_id
AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0
AND pr.book_start <= '2012-11-01'
AND pr.book_end >= '2012-11-02'
AND travel_start <= '2012-11-23'
AND travel_end >= '2012-11-30'
AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01'
AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id
Having an issue with a specific section of a query using DATEDIFF:
select 1 as NumApps,
LenderInfo.Name as LenderName,
CASE WHEN ApplicationInfo.AEType IS NULL OR ApplicationInfo.AEType = 0 THEN 'Unknown' ELSECONCAT (AEContact.FirstName, ' ', AEContact.LastName) END As AEName,
CASE WHEN b.createdby > 0 THEN CONCAT (contactinfo.firstname, ' ', contactinfo.lastname) END AS LogActionBy,
CASE WHEN ApplicationInfo.RecertificationById IS NULL THEN CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale' ELSE 'Correspondent' END ELSE CASE WHEN ApplicationInfo.IsCorrespondent IS NULL OR ApplicationInfo.IsCorrespondent = 0 THEN 'Wholesale - Recert' ELSE 'Correspondent- Recert' END END As AppType,
Applicationinfo.SubmissionDate,
ApplicationInfo.ApplicationID,
b.status AS LogStatus,
b.CreatedOn as LogDate,
companyinfo.Name,
companyinfo.NMLSEntityID,
applicationinfo.CreatedDate,
ApplicationInfo.Status as ApplicationStatus,
ApplicationInfo.StatusChangeDate,
DATEDIFF ((Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved'),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval')) AS DaysToApprove
from applicationinfo
INNER JOIN CompanyInfo ON(ApplicationInfo.CompanyId = CompanyInfo.CompanyId)
left join CompanyInfo As LenderInfo ON (ApplicationInfo.LenderId = LenderInfo.CompanyId)
LEFT JOIN UserInfo ON (UserInfo.UserId = ApplicationInfo.LastModifiedById)
LEFT JOIN ContactInfo ON UserInfo.ContactId = ContactInfo.ContactId
LEFT JOIN ContactInfo AS Comergence ON(ApplicationInfo.ComergenceRepId = Comergence.ContactId)
LEFT JOIN UserInfo AS AEUser ON(AEUser.UserId = ApplicationInfo.AEType)
left join paymentinfo on applicationinfo.applicationid = paymentinfo.applicationid
Inner join applicationstatuschangelog b on applicationinfo.applicationid = b.applicationid
LEFT JOIN ContactInfo AS AEContact ON(AEContact.ContactId = AEUser.ContactId)
LEFT JOIN UserInfo AS StatusUser ON(StatusUser.UserId = ApplicationInfo.StatusChangeById)
LEFT JOIN ContactInfo AS StatusContact ON(StatusContact.ContactId = StatusUser.ContactId)
LEFT JOIN ApprovalStatus ON(ApplicationInfo.ApplicationId = ApprovalStatus.ApplicationId AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyHQId
AND ApplicationInfo.CompanyId = ApprovalStatus.CompanyId)
Where ApplicationInfo.Status NOT In ('Approved Monitor Only')
AND LenderInfo.ActiveLenderContract = 1
AND COALESCE(ApplicationInfo.IsDeleted,0) <> 1
AND b.Status NOT IN ('Incomplete', 'Not Submitted')
Group BY b.ApplicationID`
I've seen some people mentioning using IN instead of = within the subquery, but I can't seem to get it to work. Any ideas out there? Thanks in advance.
I was able to get the query working by adding 'Limit 1' after the identified status:
(Select CreatedOn From ApplicationStatusChangeLog a where a.ApplicationId = b.ApplicationId
And a.status = 'Approved' LIMIT 1),(Select CreatedOn From ApplicationStatusChangeLog a Where a.ApplicationId = b.ApplicationId And a.status = 'Pending Approval' LIMIT 1)