alternative to nested select mysql - mysql

I am running a query at the moment, and I believe that that nest selected is creating a bottle neck, is there an alternative option that I could use?
This is my query,
SELECT post_id,
post_order,
post_parent,
post_recycle,
post_status,
post_ps_id,
post_v_id,
post_src,
post_sn_id,
post_qpc_id,
post_date_posted,
post_scheduled_local_datetime,
post_recycle_repeats,
post_recycle_expiry_date,
post_text,
post_v_title,
link_url,
link_preview_removed,
link_name,
link_description,
link_caption,
link_url_is_bitlink,
link_bitly_destination_url,
link_expanded_url,
link_initial_is_bitlink,
link_destination,
link_picture,
link_picture_size,
link_facebook_image,
link_facebook_title,
link_facebook_description,
link_facebook_caption,
link_twitter_card,
link_twitter_image,
link_twitter_title,
link_twitter_description,
pause_m_id,
qpca_evergreen_too_frequent,
sn_network,
qpc_name,
qpc_colour,
ps_m_id,
ps_filename,
ps_via,
ps_s3,
ps_width,
ps_height,
ps_gif,
video.*,
(
SELECT COUNT(*) FROM post post_inner
WHERE (post_inner.post_parent = post.post_parent)
AND post_inner.post_status = 'published'
)
AS total_repeats
FROM post
JOIN social_network ON sn_id = post_sn_id AND sn_status = 'active'
JOIN queue_post_cat ON qpc_id = post_qpc_id
LEFT JOIN queue_post_cat_account ON qpca_qpc_id = post_qpc_id AND qpca_sn_id = post_sn_id
LEFT JOIN link ON link_id = post_link_id
LEFT JOIN pause ON pause_m_id = qpc_m_id AND pause_qpc_id = post_qpc_id AND pause_sn_id = post_sn_id
LEFT JOIN photo_status ON ps_id = post_ps_id
LEFT JOIN video ON post_v_id = v_id AND v_transcoded = 1 LEFT JOIN facebook ON fb_db_id = sn_account_id AND sn_network = 'facebook'
WHERE post_status != 'now'
AND post_m_id = 1
AND qpca_sn_id IS NOT NULL
AND qpca_qpc_id IS NOT NULL
AND post_status = 'queue' AND (sn_network = 'facebook'
OR sn_network = 'instagram' OR sn_network = 'twitter')
AND qpc_m_id = 1 AND (fb_type IS NULL OR fb_type != 'profile') ORDER BY post_order ASC
I believe the bottle neck is happening here,
SELECT COUNT(*) FROM post post_inner
WHERE (post_inner.post_parent = post.post_parent)
AND post_inner.post_status = 'published'
which is select within the main select, is there something I could do that would run faster?

You can try with subquery:
select * from
(
SELECT post_id,
post_order,
post_parent,
post_recycle,
post_status,
post_ps_id,
post_v_id,
post_src,
post_sn_id,
post_qpc_id,
post_date_posted,
post_scheduled_local_datetime,
post_recycle_repeats,
post_recycle_expiry_date,
post_text,
post_v_title,
link_url,
link_preview_removed,
link_name,
link_description,
link_caption,
link_url_is_bitlink,
link_bitly_destination_url,
link_expanded_url,
link_initial_is_bitlink,
link_destination,
link_picture,
link_picture_size,
link_facebook_image,
link_facebook_title,
link_facebook_description,
link_facebook_caption,
link_twitter_card,
link_twitter_image,
link_twitter_title,
link_twitter_description,
pause_m_id,
qpca_evergreen_too_frequent,
sn_network,
qpc_name,
qpc_colour,
ps_m_id,
ps_filename,
ps_via,
ps_s3,
ps_width,
ps_height,
ps_gif,
video.*,
FROM post
JOIN social_network ON sn_id = post_sn_id AND sn_status = 'active'
JOIN queue_post_cat ON qpc_id = post_qpc_id
LEFT JOIN queue_post_cat_account ON qpca_qpc_id = post_qpc_id AND qpca_sn_id = post_sn_id
LEFT JOIN link ON link_id = post_link_id
LEFT JOIN pause ON pause_m_id = qpc_m_id AND pause_qpc_id = post_qpc_id AND pause_sn_id = post_sn_id
LEFT JOIN photo_status ON ps_id = post_ps_id
LEFT JOIN video ON post_v_id = v_id AND v_transcoded = 1 LEFT JOIN facebook ON fb_db_id = sn_account_id AND sn_network = 'facebook'
WHERE post_status != 'now'
AND post_m_id = 1
AND qpca_sn_id IS NOT NULL
AND qpca_qpc_id IS NOT NULL
AND post_status = 'queue' AND (sn_network = 'facebook'
OR sn_network = 'instagram' OR sn_network = 'twitter')
AND qpc_m_id = 1 AND (fb_type IS NULL OR fb_type != 'profile')) A
inner join
(
SELECT post_parent ,COUNT(*) FROM post where post_status = 'published' group by post_parent
) B on A.post_parent = B.post_parent
ORDER BY post_order ASC

Related

How to update multiple table using INNER JOIN and multiple SELECT

I'm trying to update 2 tables using inner Join and setting values with 2 results from variables. I've finally succeeded to have it work for a SELECT.
I want to updates my tables having a long where clause. And set the result from a select query.
Code is fine with select I get my results :
SET #DefID = "5289";
SELECT pt1.ID, pt1.post_title, pt1.post_content, mt2.meta_value
FROM wp_posts AS pt1
INNER JOIN wp_postmeta AS mt1
ON ( pt1.ID = mt1.post_id )
INNER JOIN wp_postmeta AS mt2
ON ( pt1.ID = mt2.post_id )
INNER JOIN wp_postmeta AS mt3
ON ( pt1.ID = mt3.post_id )
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'
ORDER BY mt1.meta_value ASC
But not working with UPDATE
SET #DefID = "myID";
SET #post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = #DefID );
SET #meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = #DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');
UPDATE wp_posts_bak AS pt1, wp_postmeta_bak AS mt0
INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id
SET
pt1.post_content = #post_content,
mt0.meta_value = #meta_value
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'
Got the following error : Unknown column 'pt1.ID' in 'on clause.
I finally found the reason of the problem. In the UPDATE I had to remove the 2 tables.
So the solution is :
SET #DefID = "5289";
SET #post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = #DefID );
SET #meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = #DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');
UPDATE wp_posts_bak AS pt1
INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id
SET
pt1.post_content = #post_content,
mt2.meta_value = #meta_value
WHERE
pt1.ID != #DefID
AND
pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND
mt1.meta_key = 'tourmaster-tour-date-avail'
AND
CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND
mt2.meta_key = '_cornerstone_data'
AND
mt3.meta_key = 'tourmaster-tour-duration'
AND
mt3.meta_value = '10'
AND
pt1.post_type = 'tour'
AND
pt1.post_status = 'publish'

subquery doesn't seem to work

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}

Multiple rows in a select with OR

I have this query and when I add a OR, return multiples rows, how I can fix this? I need another left join or Right join?
SELECT `images`.`id` as `id_image`, `images_lang`.`title` as `title`, `images_lang`.`autor` as `author`, `media_lang`.`file`, `category_lang`.`title` as `category`
FROM `images`
JOIN `images_lang` ON `images_lang`.`id_images` = `images`.`id`
JOIN `category_lang` ON `images`.`id_category` = `category_lang`.`id_category`
JOIN `media` ON `images`.`id` = `media`.`id_item`
JOIN `media_lang` ON `media`.`id` = `media_lang`.`id_media`
JOIN `relation` ON `relation`.`from_id` = `images`.`id`
JOIN `tag` ON `tag`.`id` = `relation`.`to_id`
JOIN `tag_lang` ON `tag`.`id` = `tag_lang`.`id_lang`
WHERE `media`.`table` = 'images'
AND `media_lang`.`id_lang` = '1'
AND `images_lang`.`id_lang` = '1'
AND `category_lang`.`id_lang` = '1'
AND `images`.`active` = 1
AND `relation`.`type` = 2
AND `tag_lang`.`id_lang` = '1'
AND `tag_lang`.`slug` = 'pa-am-oli'
OR `tag_lang`.`slug` = 'playa'
LIMIT 9
and the code in codeigniter, but I donĀ“t how add the or after the and ($keywords is an array for filter the elements)
$this->db->select('images.id as id_image, images_lang.title as title, images_lang.autor as author, media_lang.file, category_lang.title as category');
$this->db->from($this->table);
$this->db->join($this->table.'_lang',$this->table.'_lang.id_images = '.$this->table.'.id');
$this->db->join('category_lang',$this->table.'.id_category = category_lang.id_category');
$this->db->join('media',$this->table.'.id = media.id_item');
$this->db->join('media_lang','media.id = media_lang.id_media');
$this->db->where('media.table',$this->table);
$this->db->where('media_lang.id_lang',$id_lang);
$this->db->where($this->table.'_lang.id_lang', $id_lang);
$this->db->where('category_lang.id_lang', $id_lang);
$this->db->where('images.active', 1);
if($category){
$this->db->where('category_lang.title', $category);
}
if($keywords){
$this->db->join('relation', 'relation.from_id = '.$this->table.'.id');
$this->db->join('tag', 'tag.id = relation.to_id');
$this->db->join('tag_lang', 'tag.id = tag_lang.id_lang');
$this->db->where('relation.type', _IMAGES_2_TAGS_);
$this->db->where('tag_lang.id_lang', $id_lang);
foreach($keywords as $tag){
$this->db->or_where('tag_lang.slug', $tag);
}
}
if($from || $limit)
{
$this->db->limit((int)$limit, (int)$from);
}
$query = $this->db->get();
return $query->result_array();
I solved the query adding this (and a Select Distinct)
AND (`tag_lang`.`slug` = 'playa'
OR `tag_lang`.`slug` = 'pa-am-oli')
How I can add this in codeigniter?
I don't get what you need exactly, but if you want have just one line as a return by filtering using OR
In your case you should do the following:
WHERE (`media`.`table` = 'images' OR `tag_lang`.`slug` = 'playa')
AND (`media_lang`.`id_lang` = '1' OR `tag_lang`.`slug` = 'playa')
and so on, I hope that helps you and good luck!
Astute use of parentheses would solve your problem, but this is easier to read...
SELECT i.id id_image
, il.title
, il.autor author
, ml.file
, cl.title category
FROM images i
JOIN images_lang il
ON il.id_images = i.id
JOIN category_lang cl
ON cl.id_category = i.id_category
JOIN media m
ON m.id_item = i.id
JOIN media_lang ml
ON ml.id_media = m.id
JOIN relation r
ON r.from_id = i.id
JOIN tag t
ON t.id = r.to_id
JOIN tag_lang tl
ON tl.id_lang = t.id
WHERE m.table = 'images'
AND ml.id_lang = 1
AND il.id_lang = 1
AND cl.id_lang = 1
AND i.active = 1
AND r.type = 2
AND tl.id_lang = 1
AND tl.slug IN('pa-am-oli','playa')
LIMIT 9
... however, note that LIMIT without ORDER BY is fairly meaningless.

mysql complex where query

I'm trying to solve this problem for past few days any help would be appreciated.
I have a Return item which have term1 in taxonomy1 AND term2 in taksonomy2.
This is my query:
SELECT items.*
FROM (`items`)
LEFT JOIN `rel_taxonomy` ON `rel_taxonomy`.`item_id` = `items`.`id`
LEFT JOIN `terms_taxonomy` ON `terms_taxonomy`.`terms_taxonomy_id` = `rel_taxonomy`.`terms_taxonomy_id`
LEFT JOIN `terms` ON `term`.`id` = `terms_taxonomy`.`term_id`
WHERE (items.org = '2') AND ( ((terms_taxonomy.taxonomy = '1') AND (term.pojam LIKE '%term1%')) AND ((terms_taxonomy.taxonomy = '2') AND (term.pojam LIKE '%term2%')))
GROUP BY `items`.`id`
If I replace the line:
WHERE (items.org = '2') AND ( ((terms_taxonomy.taxonomy = '1') AND (term.pojam LIKE '%term1%')) AND ((terms_taxonomy.taxonomy = '2') AND (term.pojam LIKE '%term2%')))
with the following (replacing an AND with an OR):
WHERE (items.org = '2') AND ( ((terms_taxonomy.taxonomy = '1') AND (term.pojam LIKE '%term1%')) OR((terms_taxonomy.taxonomy = '2') AND (term.pojam LIKE '%term2%')))
everything works fine. But I still need AND.
Table scheme
items
id | title | org
rel_taxonomy
item_id | terms_taxonomy_id
terms_taxonomy
terms_taxonomy_id | terms_id | taxsonomy
terms
id | term
so I'm trying to get item which have term1 in taxonomy1 AND term2 in taksonomy2.
Use OR and add a HAVING clause
SELECT i.id
FROM items i
LEFT JOIN rel_taxonomy rt ON rt.item_id = i.id
LEFT JOIN terms_taxonomy tt ON tt.terms_taxonomy_id = rt.terms_taxonomy_id
LEFT JOIN terms t ON t.id = tt.term_id
WHERE i.org = '2'
AND
(
(tt.taxonomy = '1' AND t.pojam LIKE '%term1%')
OR (tt.taxonomy = '2' AND t.pojam LIKE '%term2%')
)
GROUP BY i.id
having count(distinct tt.taxonomy) = 2

DATEDIFF Subquery returns more than 1 row in mysql

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)