getting error on mysql query that I use UNION - mysql

My SQL query
SELECT DISTINCT a.*,categories_2625729.title AS category_title,categories_2625729.id AS category,c.id as cid, c.title, '' as `introtext`, 'com_hpj_content.ad' as content_type, '' as banner, '' as `fulltext`, '' as sheettext, c.publish_up, c.publish_down, c.price, c.advertiser_id, c.seller_id, c.sold, c.soldupdated,0 AS is_favorite
FROM `jos_hpj_content_item` AS a
LEFT JOIN jos_categories AS categories_2625729 ON categories_2625729.id = a.category
LEFT JOIN jos_hpj_content_item_ad AS cff ON cff.id = a.ref_id AND a.content_type = 'com_hpj_content.ad'
LEFT JOIN jos_fields_values AS fields_values_min_maxyear ON fields_values_min_maxyear.item_id = a.ref_id AND fields_values_min_maxyear.field_id=8
LEFT JOIN jos_fields_values AS fields_values_min_max_2mileage ON fields_values_min_max_2mileage.item_id = a.ref_id AND fields_values_min_max_2mileage.field_id=10
LEFT JOIN jos_hpj_content_item_ad c ON c.`id` = a.`ref_id` AND a.`content_type`='com_hpj_content.ad'
WHERE a.state = 1 AND (`c`.title LIKE '%22%' OR c.`introtext` LIKE '%22%' OR a.synonym LIKE '%22%') AND a.content_type IN ('com_hpj_content.ad') AND a.ref_id IN (53,307,353,354,572,644,717,934,978,1056,1086,1128,1149,1199,1276,1294,1314,1324,1347,1351,1396,1411,1462,1470,1513,1537,1740,1741,1836,1861,1916,1988,1989,2005,2006,2124,2158,2266,2267,2268,2277,2511,2575,2577,2582,2585,2587,2654,2815,2894,2906,2975,3021,3179,3194,3219,3224,3239,0) AND a.state = 1
UNION (SELECT name FROM jos_users WHERE name LIKE '%22%')
I'm getting error
#1222 - The used SELECT statements have a different number of columns
If I remove UNION the sql query return result but if I keep UNION the error return
I'm trying to search the number in different tables in c.title or in name from jos_user and return the result

As #danblack points out in comments, the error
#1222 - The used SELECT statements have a different number of columns
is saying that there's a different number of columns on the two SELECT statement. In
SELECT DISTINCT a.*,
categories_2625729.title AS category_title,
categories_2625729.id AS category,c.id as cid,
c.title,
'' as `introtext`,
'com_hpj_content.ad' as content_type,
'' as banner,
'' as `fulltext`,
'' as sheettext,
c.publish_up,
c.publish_down,
c.price,
c.advertiser_id,
c.seller_id,
c.sold,
c.soldupdated,0 AS is_favorite
FROM ...
..you're select a lot more columns than in this
SELECT name
FROM ...
The number of columns of those two SQL statements have to match in order for UNION to be able to add the results of the second query to the result of the first.
So this will work:
SELECT DISTINCT c.title
FROM ...
UNION
SELECT name
FROM ...
because now both individual SELECT statements return just one column.

Related

How to SUM the result of two different SQL query?

I want to SUM these two different queries. I joined both with USING function. but it shows the two results in two different cells.
I need a single result to SUM these two queries where the answer should be 4069.
The CODE
SELECT COUNT(*) Active_Projects FROM
(SELECT ProjectID, ProjectStatusID, ClientID
FROM project) a
INNER JOIN
(SELECT ProjectStatusID, ClientID, ProjectStatusName
FROM ProjectStatus) b
ON (a.ProjectStatusID = b.ProjectStatusID AND a.ClientID = b.ClientID)
WHERE ProjectStatusName LIKE '%active%'
AND a.ClientID = 4
UNION
SELECT COUNT(*) Total_Projects
FROM Project
WHERE ClientID=4
Picture
Screenshot
Screenshot Here
Try this. select query1+ query2;
select (
SELECT COUNT(*) Active_Projects FROM
(SELECT ProjectID, ProjectStatusID, ClientID
FROM project) a
INNER JOIN
(SELECT ProjectStatusID, ClientID, ProjectStatusName
FROM ProjectStatus) b
ON (a.ProjectStatusID = b.ProjectStatusID AND a.ClientID = b.ClientID)
WHERE ProjectStatusName LIKE '%active%'
AND a.ClientID = 4
) + (
SELECT COUNT(*) Total_Projects
FROM Project
WHERE ClientID=4) ;

mysql: duplicate column name on join with subquery

I've searched a lot but I still don't get it.
Here's my sample code
SELECT sp.testno, sp.companyid, st.*
FROM sponsor AS sp
LEFT JOIN
(
SELECT a.sponsorempno, (CASE WHEN t.companyid IS NULL OR t.companyid = '' THEN'aa' ELSE t.companyid END) agncy, a.controlno, a.tnpl, t.*
FROM applicant AS a
LEFT JOIN
test AS t
ON a.controlno = t.controlno
) AS st
ON sp.testno = st.testno
I still returns an error:
#1060 - Duplicate column name 'controlno'
Can somebody tell me what's wrong with the code?
In the subselect of your join, you are selecting a.controlno and by t.* t.controlno.
You should provide an alias for one of the selected columns. In your case a.controlno. This is necessary, because the table aliases of the inner select are lost, when accessing it from the outer one.
The statement below should work, if there aren't any other duplicate column names in test and the set of used columns from applicant.
SELECT sp.testno, sp.companyid, st.*
FROM sponsor AS sp
LEFT JOIN
(
SELECT a.sponsorempno, (CASE WHENt.companyid IS NULL OR t.companyid = '' THEN'aa' ELSE t.companyid END) agncy, a.controlno as a_controlno, a.tnpl, t.*
FROM applicant AS a
LEFT JOIN
test AS t
ON a.controlno = t.controlno
) AS st
ON sp.testno = st.testno

MySQL Find Most Recent/Largest Record Per Group by order by

MySQL Find Most Recent/Largest Record Per Group by order by, and how can i minimize / shorten this query and every time it returns the first row value of the group, whereas i like to select the last row value of a group, and sort the values based on ja.id ? I know this is a bad query can anyone suggest or provide me solution to shorten this query . I have used all the necessary Column Indexes in all the tables. How to shorten the query without the use of union all .both the queries in union all are same expect in the where statement.
SELECT
a.previous_status,
a.rejected_status,
a.rejection_reason_text,
a.rejection_reason,
a.rjaId,
a.refer_applied_status,
a.title,
a.playerId,
a.gameId,
a.gamePostDate,
a.game_referal_amount,
a.country,
a.country_name,
a.state,
a.location,
a.state_abb,
a.game_type,
a.appliedId,
a.appliedStatus,
a.admin_review,
a.is_req_referal_check,
a.memberId,
a.appliedEmail,
a.game_id,
a.referred_id,
a.memStateAbb,
a.memState,
a.memZipcode,
a.memCity,
a.memCountryNme,
a.memCountry,
a.appliedMemberName,
a.first_name,
a.primary_contact,
a.last_name,
a.addressbookImage,
a.userImage,
a.last_login,
a.user_experience_year,
a.user_experience_month,
a.current_designation,
a.current_player,
a.appliedDate,
a.addressbook_id,
a.joiningdate,
a.gameStatus,
a.gameReferalAmountType,
a.gameFreezeStatus,
a.gameFreezeMsg,
a.app_assign_back_to_rp_count,
a.applied_source,
a.max_id,
a.gamesApplied,
a.gamesAppliedId,
SUM(a.totalgameApplied) AS totalgameApplied,
a.application_assign_to_rp_status,
a.rpAppliedSource,
a.applied_on
FROM
(
(
SELECT
ja.previous_status,
ja.rejected_status,
ja.rejection_reason_text,
ja.rejection_reason,
rja.id AS rjaId,
rja. STATUS AS refer_applied_status,
jp.title,
jp.user_user_id AS playerId,
jp.id AS gameId,
jp.posted_on AS gamePostDate,
jp.game_referal_amount,
jp.country,
jp.country_name,
jp.state,
jp.location,
jp.state_abb,
jp.game_type,
ja.id AS appliedId,
IFNULL(ja. STATUS, '') AS appliedStatus,
IFNULL(ja.admin_review, '') AS admin_review,
ja.is_req_referal_check,
usr.id AS memberId,
rja.email AS appliedEmail,
rja.game_id,
rja.referred_id,
mem.state_abb AS memStateAbb,
mem.state AS memState,
mem.zipcode AS memZipcode,
mem.city AS memCity,
mem.country_name AS memCountryNme,
mem.country_code AS memCountry,
usc. NAME AS appliedMemberName,
usc.first_name,
IFNULL(
mem.primary_contact,
usc.phone_number
) AS primary_contact,
usc.last_name,
usc.profileimage_path AS addressbookImage,
usr.profile_image AS userImage,
usr.last_login,
mem.user_experience_year,
mem.user_experience_month,
mem.current_designation,
mem.current_player,
rja.create_date AS appliedDate,
rja.addressbook_id,
IFNULL(ja.joining_date, '') AS joiningdate,
jp. STATUS AS gameStatus,
jp.games_referal_amount_type AS gameReferalAmountType,
jp.game_freeze_status AS gameFreezeStatus,
jp.game_freeze_message AS gameFreezeMsg,
ja.app_assign_back_to_rp_count,
ja.applied_source,
MAX(rja.id) AS max_id,
GROUP_CONCAT(
jp.title
ORDER BY
rja.create_date DESC
) AS gamesApplied,
GROUP_CONCAT(DISTINCT(jp.id)) AS gamesAppliedId,
COUNT(DISTINCT(jp.id)) totalgameApplied,
ja.application_assign_to_rp_status,
1 AS rpAppliedSource,
rja.create_date AS applied_on
FROM
(`refer_gameapplied` AS rja)
JOIN `games_post` AS jp ON `jp`.`id` = `rja`.`game_id`
JOIN `user_socialconnections` AS usc ON `rja`.`addressbook_id` = `usc`.`id`
LEFT JOIN `user_user` AS usr ON `usr`.`email` = `rja`.`email`
LEFT JOIN `user_member` AS mem ON `mem`.`user_id` = `usr`.`id`
LEFT JOIN `game_applied` AS ja ON `ja`.`id` = `rja`.`applied_id`
WHERE
`rja`.`referby_id` = '2389'
GROUP BY
`rja`.`email`
)
UNION ALL
(
SELECT
ja.previous_status,
ja.rejected_status,
ja.rejection_reason_text,
ja.rejection_reason,
jr.id AS rjaId,
jrtm. STATUS AS refer_applied_status,
jp.title,
jp.user_user_id AS playerId,
jp.id AS gameId,
jp.posted_on AS gamePostDate,
jp.game_referal_amount,
jp.country,
jp.country_name,
jp.state,
jp.location,
jp.state_abb,
jp.game_type,
ja.id AS appliedId,
IFNULL(ja. STATUS, '') AS appliedStatus,
IFNULL(ja.admin_review, '') AS admin_review,
ja.is_req_referal_check,
usr.id AS memberId,
jrtm.referto_email AS refappliedEmail,
jr.game_id,
jrtm.id,
mem.state_abb AS memStateAbb,
mem.state AS memState,
mem.zipcode AS memZipcode,
mem.city AS memCity,
mem.country_name AS memCountryNme,
mem.country_code AS memCountry,
usc. NAME AS appliedMemberName,
usc.first_name,
IFNULL(
mem.primary_contact,
usc.phone_number
) AS primary_contact,
usc.last_name,
usc.profileimage_path AS addressbookImage,
usr.profile_image AS userImage,
usr.last_login,
mem.user_experience_year,
mem.user_experience_month,
mem.current_designation,
mem.current_player,
jrtm.refer_on AS appliedDate,
jrtm.referto_addressbookid,
IFNULL(ja.joining_date, '') AS joiningdate,
jp. STATUS AS gameStatus,
jp.games_referal_amount_type AS gameReferalAmountType,
jp.game_freeze_status AS gameFreezeStatus,
jp.game_freeze_message AS gameFreezeMsg,
ja.app_assign_back_to_rp_count,
ja.applied_source,
MAX(jrtm.id) AS max_id,
GROUP_CONCAT(
jp.title
ORDER BY
jr.refer_on DESC
) AS gamesApplied,
GROUP_CONCAT(DISTINCT(jp.id)) AS gamesAppliedId,
COUNT(DISTINCT(jp.id)) totalgameApplied,
ja.application_assign_to_rp_status,
2 AS rpAppliedSource,
jrtm.refer_on AS applied_on
FROM
(`game_refer` AS jr)
JOIN `game_refer_to_member` AS jrtm ON `jrtm`.`rid` = `jr`.`id`
JOIN `games_post` AS jp ON `jp`.`id` = `jr`.`game_id`
JOIN `user_socialconnections` AS usc ON `jrtm`.`referto_addressbookid` = `usc`.`id`
LEFT JOIN `user_user` AS usr ON `usr`.`email` = `jrtm`.`referto_email`
LEFT JOIN `user_member` AS mem ON `mem`.`user_id` = `usr`.`id`
LEFT JOIN `game_applied` AS ja ON `ja`.`referred_by` = `jrtm`.`id`
WHERE
`jrtm`.`status` = '1'
AND `jr`.`referby_user_id` = '2389'
AND `jrtm`.`refer_source` NOT IN ('4')
GROUP BY
`jrtm`.`referto_email`
)
) a
GROUP BY
a.appliedEmail
ORDER BY
a.gamesAppliedId DESC
It sounds like a "groupwise-max" problem. I added a tag that you should research.
At least get rid of the columns that are not relevant to the question.
Try tossing the tables other than jrtm and jr to see if the performance problem persists. (I'm thinking that the LEFT JOINs may be red herrings.)
Try with one part of the UNION, then with the other. This may identify which of the two is more of a burden.
Some indexes to add:
rja: (referby_id, create_date)
jrtm: (status, referto_email)
jrtm: (rid, status, referto_email)
jr: (referby_user_id, refer_on)
DISTINCT is not a function. Don't use parents in DISTINCT(jp.id).

mysql combine 2 queries from same table

This is query 1:
SELECT distinct c.chem_gene, m.String_name, m.ScopeNote
FROM mesher m INNER JOIN chem_base c
ON (c.chem_name = m.String_name AND m.ScopeNote <> '' )
where match (c.chem_gene) against('ACTN3, MTHFR' in boolean mode)
group by c.chem_gene, c.chem_name;
which outputs 3 columns in rows like this:
'ACTN3', 'Estradiol', 'The 17-beta-isomer of estradiol...'
This is query 2 (taking the output from column 2, "Estradiol"):
SELECT String10 FROM mesher where String_name = "Estradiol" AND String10 <>'' LIMIT 1;
which outputs a single row in a single column:
'Estrogens'
How can I modify query 1 so that for each row returned the additional query is made against the result in the second column (i.e.'Estradiol') to produce this output:
'ACTN3', 'Estradiol', 'The 17-beta-isomer of estradiol...', 'Estrogens'
If I understand correctly, you can use a correlated subquery:
SELECT c.chem_gene, m.String_name, m.ScopeNote,
(SELECT mm.String10
FROM mesher mm
WHERE mm.String_name = m.String_name AND mm.String10 <> ''
LIMIT 1
)
FROM mesher m INNER JOIN
chem_base c
ON c.chem_name = m.String_name AND m.ScopeNote <> ''
WHERE match(c.chem_gene) against( 'ACTN3, MTHFR' in boolean mode)
GROUP BY c.chem_gene, c.chem_name, m.ScopeNote ;
The select distinct is not necessary.

No column name specified for column number in derived table

I am getting this error message, can someone advise on a solution?
I have looked over this forum and cant find a solution
Dynamic SQL Error
SQL error code = -104
Invalid command
no column name specified for column number 1 in derived table ACCRG
SELECT DISTINCT locationgroup.name AS MainGroup, product.num AS ProductNumber,
product.description AS ProductDescription, uom.code AS UOM, company.name AS company,
sum(((SELECT SUM(productsSold.qtyfulfilled) FROM soitem productsSold WHERE soitem.id = productsSold.id AND productsSold.productid = product.id) * COALESCE(uomconversion.multiply,1)) / COALESCE(uomconversion.factor,1)) AS uomqty
FROM soitem
LEFT OUTER JOIN so ON (so.id = soitem.soid)
LEFT OUTER JOIN product ON (soitem.productid = product.id)
LEFT OUTER JOIN uom ON (product.uomid = uom.id)
LEFT OUTER JOIN locationgroup ON (so.locationgroupid = locationgroup.id)
LEFT OUTER JOIN qbclass ON (qbclass.id = soitem.qbclassid)
LEFT OUTER JOIN customer ON (customer.id = so.customerid)
LEFT JOIN (SELECT max(accountgrouprelation.id) AS relationID, accountgrouprelation.accountid
FROM accountgrouprelation
LEFT JOIN accountGroup ON accountGroupRelation.groupId = accountGroup.id
WHERE UPPER(COALESCE (accountgroup.name, '%')) LIKE UPPER('%')
GROUP BY 2) accrg ON customer.accountid = accrg.accountid
LEFT JOIN accountgrouprelation ON accrg.relationid = accountgrouprelation.id
LEFT OUTER JOIN accountgroup ON (accountgroup.id = accountgrouprelation.groupid)
LEFT OUTER JOIN uomconversion ON ((product.uomid = uomconversion.touomid) AND (soitem.uomid = uomconversion.fromuomid))
JOIN company ON company.id = 1
WHERE soitem.qtyfulfilled > 0
AND soitem.typeid in (10,12,80)
AND locationgroup.id IN (1,2,3,4)
AND qbclass.id LIKE '%'
AND UPPER(so.salesman) LIKE UPPER('%')
AND UPPER(COALESCE (accountgroup.name, '%')) LIKE UPPER('%')
AND soitem.datelastfulfillment BETWEEN '2015-11-30 23:59:59.0' AND '2015-12-31 23:59:59.0'
GROUP BY maingroup, productnumber, productdescription, uom, company
ORDER BY 1,product.num ASCENDING
Believe it or not, I think the error is coming from your ORDER BY statement:
ORDER BY 1,product.num ASCENDING
I don't believe it is legal to ORDER BY a constant number in MySQL. Telling by the error, it appears that MySQL is trying to find a column called 1 in the ACCRG derived table. No such column exists, hence you are getting this error. Instead, why not just ORDER BY the product number?:
ORDER BY product.num ASCENDING