Select Record Conditional Random #MySQL - mysql

I have two tables, one for still images and one with this property, both are linked so that a property can have no pictures. Would you like to "select" where I can select all properties and just a random picture of this property. How to do this?
Exemplifying best, I pick a random image from the image table for each record in the table that has motionless pictures. Want to select this randomly. What I could do was to select all images for each record of the bank property. I just want each record imovel a respective random image.
The sql is below:
select distinct
imovel.nome as 'NOME',
imovel.valor as 'VALOR',
imovel.quarto as 'QUARTO',
imovel.suite as 'SUITE',
cidade.nome as 'CIDADE',
bairro.nome as 'BAIRRO',
(select distinct nome from tabimagem img where img.cdimovel = imagem.cdimovel order by rand() limit 1) as 'IMAGEM'
from tabimovel imovel
inner join tabcidade cidade on imovel.cdcidade = cidade.codigo
inner join tabbairro bairro on imovel.cdBairro = bairro.codigo
inner join tabimagem imagem on imagem.cdImovel = imovel.codigo
order by rand()

In SQL server add TOP 1 after SELECT, and order as ORDER BY NEWID().
In MySQL, order should be ORDER BY RAND(), followed by LIMIT 1.
That should work.

Related

GROUP BY clause and contains nonaggregated column issue solve without disabling full groupby variable from SQL

I am facing some groupby aggregation issue in my below join query:
SELECT chat_tbl.chatrec_id,
chat_tbl.senderid,
chat_tbl.receiverid,
chat_tbl.msg,
chat_tbl.chat_time,
chat_tbl.chatuser_strid,
chatuser_link_tbl.str_id,
chatuser_link_tbl.modifytime
FROM chat_tbl
INNER JOIN chatuser_link_tbl ON chat_tbl.chatuser_strid = chatuser_link_tbl.str_id
AND (chat_tbl.senderid=393 OR chat_tbl.receiverid=393)
GROUP by chat_tbl.chatuser_strid
ORDER by chatuser_link_tbl.modifytime DESC
I know I can disable the only_full_group_by setting by executing the following:
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
But that is the wrong method it will waive off the settings and this is again removed after every server restart so i want to correct my query. Please anyone can help me to correctly write this join query from 3 tables.
Thanks in advance.
Update 1: I am using this query to list all the chat done by the current user with other users.
I have 2 tables to do that chatuser_link_tbl has the link of the chat done between 2 users for example 11-18, 12-22 i.e concatenated 2 user id with dash - and chat table has an actual chat data.
I am using group by to group all the chats using chatuser_strid to get only single last record. I am displaying only last chat message with date time.
In short this is the same as whatsapp chat list (the first home screen) or like facebook messenger chat list. Which display user details with their last chat message.
Since your query is designed to work on a single user (sender or receiver equal to 393) you can simply drop the group by and add a limit
SELECT chat_tbl.chatrec_id,
chat_tbl.senderid,
chat_tbl.receiverid,
chat_tbl.msg,
chat_tbl.chat_time,
chat_tbl.chatuser_strid,
chatuser_link_tbl.str_id,
chatuser_link_tbl.modifytime
FROM chat_tbl
INNER JOIN chatuser_link_tbl ON chat_tbl.chatuser_strid = chatuser_link_tbl.str_id
AND (chat_tbl.senderid=393 OR chat_tbl.receiverid=393)
ORDER by chatuser_link_tbl.modifytime DESC
LIMIT 1
I think you want to use window functions for this:
SELECT *
FROM (SELECT c.*, cl.str_id, cl.modifytime,
ROW_NUMBER() OVER (PARTITION BY c.chat_user_strid ORDER BY cul.modifytime DESC)
FROM chat_tbl c JOIN
chatuser_link_tbl cul
ON c.chatuser_strid = cul.str_id AND
393 IN (c.senderid, c.receiverid)
) c
WHERE seqnum = 1;
I have fixed the issue myself. Below query worked for me to get desired result.
ANY_VALUE helped me.
SELECT chat_tbl.chatuser_strid, ANY_VALUE(chat_tbl.chatrec_id),ANY_VALUE(chat_tbl.senderid),ANY_VALUE(chat_tbl.receiverid),ANY_VALUE(chat_tbl.msg),ANY_VALUE(chat_tbl.chat_time), ANY_VALUE(chatuser_link_tbl.str_id)
FROM chat_tbl
INNER JOIN chatuser_link_tbl
ON chat_tbl.chatuser_strid = chatuser_link_tbl.str_id AND (chat_tbl.senderid=".$userid." OR chat_tbl.receiverid=".$userid.")
GROUP by chat_tbl.chatuser_strid
ORDER by ANY_VALUE(chatuser_link_tbl.modifytime) DESC

Select data from table using SQL query

I have a table name "chat_details" I wanna access only data with green underline according to time, I use the following query
//suppose $user_id = 1;
"SELECT *
FROM chat_details WHERE from_user_id='$user_id' OR to_user_id='$user_id' ORDER BY time DESC"
It fetch all the rows because all rows contain user_id = 1 in one of the column, but i need only green underline rows as compare to red one because green one are latest according to time(column), how can i fetch only these green underlines?
This is one posible query, that should solve your question.
SELECT *
FROM chat_details c
WHERE (c.from_user_id='$user_id' OR c.to_user_id='$user_id')
AND NOT EXISTS (
SELECT 1 FROM chat_details d
WHERE d.from_user_id = c.from_user_id
AND d.to_user_id = c.to_user_id
AND d.time > c.time)
ORDER BY c.time DESC"
Actually I could not test, hope I haven't made a mistake.
The query selects all data as in your query, but only thoose which haven't a newer chat between the two users.
For the EXISTS keyword see http://www.mysqltutorial.org/mysql-exists/

MySQL multiple joins and count distinct

I need to write query that joins several tables and I need distinct value from one table based on max count().
These are my tables names and columns:
bands:
db|name|
releases_artists:
release_db|band_db
releases_styles
release_db|style
Relations between tables are (needed for JOINs):
releases_artists.band_db = bands.db
releases_styles.release_db = releases_artists.release_db
And now the query that I need to write:
SELECT b.name, most_common_style
LEFT JOIN releases_artists ra ON ra.band_db = b.db
and here I need to find the most common style from all band releases
JOIN(
SELECT DISTINCT style WHERE releases_styles.release_db = ra.release_db ORDER BY COUNT() DESC LIMIT 1
)
FROM bands b
WHERE b.name LIKE 'something'
This is just a non working example of what I want to accomplish. It would be great if someone could help me build this query.
Thanks in advance.
EDIT 1
Each artist from table bands can have multiple records from releases_artists table based on band_db and each release can have multiple styles from releases_styles based on release_db
So if I search for b.name LIKE '%ray%' it returns something similar to:
`bands`:
o7te|Ray Wilson
9i84|Ray Parkey Jr.
`releases_artists` for Ray Wilson:
tv5c|o7te (for example album `Change`)
78wz|o7te (`The Next Best Thing`)
nz7c|o7te (`Propaganda Man`)
`releases_styles`
tv5c|Pop
tv5c|Rock
tv5c|Alternative Pop/Rock
----
78wz|Rock
78wz|Pop
78wz|Classic Rock
I need style name that repeats mostly from all artist releases as this artist main style.
Ok, this is a bit of a hack. But the only alternatives I could think of involve heaps of nested subqueries. So here goes:
SELECT name
, SUBSTRING_INDEX(GROUP_CONCAT(style ORDER BY release_count DESC SEPARATOR '|'), '|', 1) AS most_common_style
FROM (
SELECT b.db
, b.name
, rs.style
, COUNT(*) AS release_count
FROM bands b
JOIN releases_artists ra ON ra.band_db = b.db
JOIN releases_styles rs ON rs.release_db = ra.release_db
GROUP BY b.db, rs.style
) s
GROUP BY db;

Select only distinct values for a particular column mysql

We have two tables in mysql database.Screenshots are attached below.
Given table ads_testTable
here is the screenshot of my dimesnionvalue_flattable
We have to run a query like the one below.
SELECT Quiz_Attempt.L1_Key dimID,
Quiz_Attempt.L1_Label CatVars,
COALESCE(**xyz**,0) AS series0
FROM DSQ_ADSSCHEMA.ADS_TestTable dataTable
RIGHT OUTER JOIN LS_CONFIG.DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY Quiz_Attempt.L1_Key, Quiz_Attempt.L1_Label;
My motive is to write a query in place of xyz so that I can get avg of obtainedMarks column in testtable according to the value of dimID I get.Each distinct Quiz_Attempt is a different test so If a Packet is repeating for a particular Quiz_Attempt in testTable, it should take only one value for that AttemptID.
I think you query could take the form of:
SELECT
L1_Key dimID,
L1_Label CatVars,
COALESCE('**xyz**',0) AS series0
FROM (
SELECT *
FROM (SELECT * FROM ADS_TestTable GROUP BY ADS_TestTable.Quiz_Attempt) dataTable
RIGHT OUTER JOIN DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY dataTable.Quiz_Attempt
) A GROUP BY dimID, CatVars;
The JOIN is done in an inner query, and grouped by Quiz_Attempt, so that you get a single row per attempt. This result is then used to compute what you need.

select the first row of a joined database

I need to select the first row of a database joined with another main database.
The main database collects informations about dogs, their race, size, name eccc…
The joined database is linked to the frist and provide dog’s images.
Each dog has different images, more than one.
In the list page of the dogs, I need to show, for each dog, all dog’s details and only the frist image of the joined database, as it was the profile image.
So here u are the structure of the two databases:
//dog_pages database:
id
--
slug
--
name
--
race
--
size
--
description
--
created
--
updated
and:
//dog_images database:
id
--
dog_page_id //this is for the join
--
content
--
img_title
--
img_url
--
img_ftp_path
--
thumb_ftp_path
--
thumb_delete_path
I use this code to generate the query:
SELECT dog_pages.id, dog_pages.slug, dog_pages.name, dog_pages.race, dog_pages.size, dog_pages.description, dog_pages.created, dog_pages.updated, dog_images.id, dog_images.dog_page_id, dog_images.img_url, dog_images.thumb_ftp_path, dog_images.content AS image_content
FROM dog_pages
LEFT JOIN dog_images
ON dog_pages.id = (
SELECT dog_images.dog_page_id
FROM dog_images
WHERE dog_pages.id = dog_images.dog_page_id
LIMIT 1
)
Unfortunately this doesn’t work, the results is to have more than one image for each dog. I needjust one, that in the frist row of the dog_images.
There are multiple methods (including variables). But, taking your method, you can use an aggregation function instead of limit:
SELECT p.id, p.slug, p.name, p.race, p.size, p.description, dog_pages.created, p.updated,
i.id, i.dog_page_id, i.img_url, i.thumb_ftp_path, dog_images.content AS image_content
FROM dog_pages p LEFT JOIN
dog_images i
ON p.id = i.dog_page_id AND
i.id = (SELECT MIN(i2.id)
FROM dog_images i2
WHERE p.id = i2.dog_page_id
);
In the second select you are choosing only Id for joining and you can replace it just with
..=dog_images.dog_page_id
It's exactly what you get from the select
To solve the problem try to use group by dog_pages_I'd
And you should get information only about one image