MYSQL nested select query from same table - mysql

What I am trying to do is select each distinct column1 value from table1 and then select all the columns from those rows returned from the above. Is this possible at all?
What I have so far, however, nothing is returned:
SELECT * FROM (SELECT DISTINCT column1 FROM table1)
I've thought about putting a unique/distinct restriction in the where clause of the query:
SELECT * FROM table1 WHERE some_unique_determiner column1
Any ideas how I could go about achieving the desired output?

Ok so answering my own question. What I need to do was to group the data by column1, without use of a nested query. Many thanks to #VR46 for the help.
SELECT * FROM table1 GROUP BY column1
Returned all columns from each unique value from column1

In your next posts, it will be better if you post your table structures, input and desired out put so it will be easier for us to understand.
If I did understand, there is one of two options:
Either you have duplicates, and you want to eliminate them so your correct query should be
select distinct COLUMNa,COLUMNb,COLUMNc... ETC
which will drop duplicates(that the entire row is the same).
Or you want to eliminate rows that have the same column1 and it doesn't matter if all the rest is the same or not.
In that case, You need to tell us which one of the result you want to keep, The up to date one,the older, random ETC.. because right now its impossible to make you a query that selects all the columns after you distinct, since all the duplicates will return like this:
SELECT * FROM TABLE WHERE COLUMN1 IN(SELECT DISTINCT COLUMN1 FROM TABLE)
Which is a wrong query since it doesn't do anything.

Related

What is the correct MySQL syntax for a query with a COUNT from another table as a column?

Here is a query I've used that almost does what I want:
SELECT *, COUNT(p.prize_id) as number_prizes
FROM tbl_draw d
INNER JOIN tbl_prize p ON p.draw_id=d.draw_id
WHERE d.draw_id={$draw_id}
The key point is that it counts the number of items from tbl_prize that matches on draw_id and presents that number as a new column 'number_prizes' in the result set. For this query, the result set is a single row, because of the final WHERE clause that matches on a specific draw_id.
I want it to return ALL of the rows from tbl_draw with that same calculation per row. My problem is that when I remove the final clause "WHERE d.draw_id={$draw_id}", the result collapses all the rows into one, and is only sending back the first such row found in tbl_draw and with 'number_prizes' being a total of all
How can I phrase the query better?
You need to add a group by clause, naming all columns, eg:
<your query>
group by col1, col2, ... -- list all other columns
As said above, you should use the group by after the end of your query, like this:
SELECT *, COUNT(p.prize_id) as number_prizes
FROM tbl_draw d
INNER JOIN tbl_prize p ON p.draw_id=d.draw_id
WHERE d.draw_id={$draw_id}
GROUP BY col1, col2, col3, coln.....
And, if you want the id from tbl_draw, your SELECT must be like:
SELECT d.id as draw_id, *, COUNT(p.prize_id) as number_prizes
I strongly recommend that you do not use SELECT *, ... here. List all of the columns that form the groups within the SELECT clause, then repeat that list within GROUP BY.
Here's why: "SELECT * will work only until someone adds a column to that table!" Which of course will happen someday.
Then, all of the sudden, your query will start failing, because * references this new column (which presumably you don't care about anyway ...), which is not in the GROUP BY list as is required.
Always specify exactly what columns (and aggregate functions ...) your query needs. You'll be very glad you did. (And so will your co-workers!)

Merging multiple queries preferentially

I'd like to be able to merge two sorted queries, and merge them, preferring things in the first query (i.e. except for duplicates, everything in the first query is favored over everything in the second query). Better still, I'd be able to do this with one query, rather than multiple queries (although I'm not too picky).
For example, if the first query returned:
"Apple"
"Bat"
"Dolphin"
And the second one returned:
"Cat"
"Dolphin"
"Elephant"
I'd want the results to look like this:
"Apple"
"Bat"
"Dolphin"
"Cat"
"Elephant"
If it helps, I'm trying to implement a search feature, but want it to be flexible. The first query may be things that exactly match, the second may be things that begin with the query string, and a third, for example, may be things that contain the query string anywhere.
Each query is a superset of the previous query.
You could achieve by using UNION to select values from all tables and giving each table an order value.
select distinct Word
from
(
select Word, 1 as WordOrder from table1
union
select Word, 2 as WordOrder from table2
) X
order by WordOrder
SQL Fiddle demo
I would suggest to do a union select. You can use different conditions in where for each query and merge the result:
SELECT * FROM table1
WHERE ...
UNION
SELECT * FROM table1
WHERE ...
You can even merge the result from different tables, if the columns in result are the same in all querys:
SELECT * FROM table1
WHERE ...
UNION
SELECT * FROM table2
WHERE ...

Query to be fine tuned

This being my first question in SO
I am using a query which is ::
SELECT column1, column2, COUNT(*)
FROM myTable
GROUP BY DATE(logged_date)
HAVING COUNT(*)>10
Mytable contaings 2 million records, and the column logged_date is of type datetime.
The above query is takink aroud 15 seconds to execute.
Any help will be appreciated.
Welcome.
It would be best to also provide the table schema. Nevertheless, I will make some guesses:
The logged_date is a TIMESTAMP column or a DATATIME -- is that so? Which is the reason for doing DATE() on that column.
Your best option, if this is a query you wish to optimize, is to add another column, which is logged_date_day (the first name is already confusing, the second as much :) )
This means supporting both at the same time (but my next guess is that you only INSERT it one, not to be update again -- so this is not too much of an effort).
You would then have to index the new column, and do the GROUP BY on that column.
PS
Technically speaking, SELECT column1 FROM some_table GROUP BY another_column is not a valid query. MySQL allows it when your sql_mode does not contain ONLY_FULL_GROUP_BY. I recommend that you look into this.
I am also worried about grouping on logged_date but showing column1 and 2, this might not give you the expected results, so better to group on all cols or use a function like max or min around column1 and 2
nevertheless, you might consider something like this :
make sure everything in the group by is keyed togther:
alter table myTable add key (logged_date (10), column1,column2);
changed query :
SELECT left(logged_date,10) as ldate , column1, column2, COUNT(*)
FROM myTable
GROUP BY ldate,column1,column2
HAVING COUNT(*)>10

SELECT command in mysql

I was wondering if there is a way to do something like selecting all without ... some columns here
something like SELECT */column1,column2 , is there a way to do this ?
I just need to output something like
column1 , column2 ( from another table ) , here all other columns without column1 ( or something to make the select skip the first few columns)
EDIT:
The thing is that i need this to be dynamic , so i cant just select what i don't know. I never know how many columns there will be , i just know the 1st and the 2nd column
EDIT: here is a picture http://oi44.tinypic.com/xgdyiq.jpg
I don't need the second id column , just the last column like i have pointed.
Start building custom views, which are geared aorund saving developers time and encapsulating them from the database schema.
Oh, so select all but certain fields. You have two options.
One is a little slow.. Copy the table, drop the fields you don't want, then SELECT *
The other is to build the field list from a subquery to information_schema or something, then remove occurrences of 'field_i_dont_want' in that list.
SELECT ( SELECT THE TABLES YOU WANT AND CONCAT INTO ONE STRING ) FROM TABLE
If you need to combine records from multiple tables, you need to find a way to relate them together. Primary Keys, Foreign Keys, or anything common among this.
I will try to explain this with a sql similar to your problem.
SELECT table1.id, table2.name, table1.column3, table1.column4
FROM table1
INNER JOIN table2 On table2.commmonfield = table1.commonfield
If you have 'n' columns in your table as in Col1,Col2,Col3....Coln you can select whatever columns you want to select from the table.
SELECT Col1,Col2 FROM YOURTABLE;
You either select all columns (*) or especify the columns you want one by one. There is no way to select 'all but some'.
The SQL language lets you either select a wildcard set of columns or enumerated single columns from a singular table. However you can join a secondary table and get a wildcard there.
SELECT
a.col1,
b.*
FROM
table_a as a
JOIN table_b as b ON (a.col5 = b.col_1)

MySQL GROUP BY Multiple Columns

I need to perform a GROUP BY on 2 columns separately...
In common terms, I'd like the query to say: GROUP BY column 1, then once this grouping has been performed, and the rows returned have been refined, go back to the top and GROUP BY column 2 to refine the rows returned again.
For instance, instead of stating:
GROUP BY column_1, column_2
I want to state (I Understand this is incorrect syntax):
GROUP BY column_1
GROUP BY column_2
If this is unclear I can include a sample query with expected returned results.
Are you trying to do something like this?
select ...
from (
select ...
from some_table
where ...
group by column1
) as dt
group by column2
That's the closest thing I can think of that matches what your question appears to be asking.
Mostly you can group by multiple columns in mysql. The query is:select * from table group by col1, col2
But you can't get answer as you want as. So you've another chance to get correct answer in mysql. That is, you've to use subqueries.select * from (select * from table group by col2) tabl group by col1