Duplicating rows in one select MySql query - mysql

At first I would like greet all Users and apologize for my english :).
I'm new user on this forum.
I have a question about MySQL queries.
I have table Items with let say 2 columns for example itemsID and ItemsQty.
itemsID ItemsQty
11 2
12 3
13 3
15 5
16 1
I need select itemsID but duplicated as many times as indicated in column ItemsQty.
itemsID ItemsQty
11 2
11 2
12 3
12 3
12 3
13 3
13 3
13 3
15 5
15 5
15 5
15 5
15 5
16 1
I tried that query:
SELECT items.itemsID, items.itemsQty
FROM base.items
LEFT OUTER JOIN
(
SELECT items.itemsQty AS Qty FROM base.items
) AS Numbers ON items.itemsQty <=Numbers.Qty
ORDER BY items.itemsID;
but it doesn't work correctly.
Thanks in advance for help.

SQL answer - Option 1
You need another table called numbers with the numbers 1 up to the maximum for ItemsQuantity
Table: NUMBERS
1
2
3
4
5
......
max number for ItemsQuantity
Then the following SELECT statement will work
SELECT ItemsID, ItemsQty
FROM originaltable
JOIN numbers
ON originaltable.ItemsQty >= numbers.number
ORDER BY ItemsID, number
See this fiddle -> you should always set-up a fiddle like this when you can - it makes everyone's life easier!!!
code answer - option 2
MySQL probably won't do what you want 'cleanly' without a second table (although some clever person might know how)
What is wrong with doing it with script?
Just run a SELECT itemsID, ItemsQty FROM table
Then when looping through the result just do (pseudo code as no language specified)
newArray = array(); // new array
While Rows Returned from database{ //loop all rows returned
loop number of times in column 'ItemsQty'{
newArray -> add 'ItemsID'
}
}//end of while loop
This will give you a new array
0 => 11
1 => 11
2 => 12
3 => 12
4 => 12
5 => 13
etc.

Select DISTINCT items.itemsID, items.itemsQty From base.items left outer join (select items.itemsQty as Qty from base.items) As Numbers On items.itemsQty <=Numbers.Qty
order by items.itemsID;
Use DISTINCT to remove duplicates. Read more here - http://dev.mysql.com/doc/refman/5.0/en/select.html

It seems like I understood what you asked differently than everyone else so I hope I answer you question. What I would basically do is -
create a new table for those changes.
Create a mysql procedure which given a line in the original table add new lines to the new table - http://dev.mysql.com/doc/refman/5.6/en/loop.html
Run this procedure for each line in the original table.

try this to get distinct values from both columns
SELECT DISTINCT itemsID FROM items
UNION
SELECT DISTINCT itemsQty FROM items

Related

cannot use AND with the same argument in mysql

select producten_pid from prodsymp where symptomen_id = 11 and symptomen_id = 18;
I am trying the select statement above on a mysql table.
But I am not getting any results, where I should.
What am I doing wrong?
Thank you for your answers.
The idea was to create a database for problems and solutions,
where one problem can have multiple solutions and one solution can solve multiple problems.
I created this reference table 'probsol' with references to both the problems and the solutions table like below.
psid 1 2 3 4 5 6 7 8 9
pid 11 11 12 12 17 18 18 19 20
sid 18 9 18 10 10 18 9 13 13
Now I am trying to create a query to find lets say a single solution to multiple problems as below:
select sid from prodsymp where pid = 11 and pid = 12;
The results for this query should be 18, but I am getting 0 results.
Mysql is working as expected. You ask for a row where symptomen_id is at the same time 11 and 18. There can be no such row, so you don't get any result.
Maybe you wanted to use OR.
Your logic is wrong. symptomen_id can't be both at the same time. Use or.
Even better, use in like so:
select producten_pid from prodsymp where symptomen_id in (11, 18).
Edit:
Afer you edited your question, your problem became quite different.
Maybe this query can help:
SELECT
sid,
count(*) as cnt
FROM
producten_pid
where
pid in (
11,12
)
group by
sid
having
count(*) > 1

MYSQL Can WHERE IN default to ALL if no rows returned

Have a existing table of results like this;
race_id race_num racer_id place
1 0 32 2
1 1 32 3
1 2 32 1
1 3 32 6
1 0 44 2
1 1 44 2
1 2 44 2
1 3 44 2
etc...
Have lots of PHP scripts that access this table output the results in a nice format.
Now I have a case where I need to output the results for only certain race_nums.
So I have created this table races_included.
race_view race_id race_num
Day 1 1 0
Day 1 1 1
Day 2 1 2
Day 2 1 3
And can use this query to get the right results.
SELECT racer_id, place from results WHERE race_id=1
AND race_num IN
(SELECT race_num FROM races_included WHERE race_id='1' AND race_view='Day 1')
This is great but I only need this feature for a few races and to have it work in a compatible mode for the simple case show all races. I need to add alot of rows to the races_included table. Like
race_view race_id race_num
All 1 0
All 1 1
All 1 2
All 1 3
95% of my races don't use the daily feature.
So I am looking for a way to change the query so that if for race 1 there are no records in the races_included table it defaults to all races. In addition I need it to be close the same execution speed as the query without the IN clause, because this query Or variations of it are used a lot.
One way that does work is to redefine the table as races_excluded and use NOT IN. This works great but is a pain to manage the table when races are added or deleted.
Is there a simple way to use EXISTS and IN in tandem as a subquery to get the desired results? Or some other neat trick I am missing.
To clarify I have found a working but very slow solution.
SELECT * FROM race_results WHERE race_id=1
AND FIND_IN_SET(race_num, (SELECT IF((SELECT Count(*) FROM races_excluded
WHERE rid=1>0),(SELECT GROUP_CONCAT(rnum) FROM races_excluded
WHERE rid=1 AND race_view='Day 1' GROUP BY rid),race_num)))
It basically checks if any records exists for that race_id and if not return a set equal to the current race_num and if yes returns a list of included race nums.
You can do this by using or in the subquery:
SELECT racer_id, plac
from results
WHERE race_id = 1 AND
race_num IN (SELECT race_num
FROM races_included
WHERE race_id = '1' AND (race_view = 'Day 1' or raw_view = 'ANY')
);

Query that returns quantity of repeated values

In mysql, I need a query that returns the quantity of repeated values in the field "Info" of my table "Log".
Table Log:
ID_Log User Info
1 1 3
2 1 3
3 1 3
4 1 5
5 1 6
6 1 6
7 1 7
8 1 8
9 1 8
The query should return "4" (Info 3 appears three times, Info 6 appears two times, Info 8 appears two times).
Any suggestions?
You can get the number of values that have already appeared by using a simple subtraction. Subtract the number of distinct values from the total number of rows:
select count(*) - count(distinct info)
from log;
The difference is the number that "repeat".
This should work. Group the values of info together and only keep the results where the number of occurrences minus 1 is greater than 0. Then sum the numbers of occurrences.
select sum(repeats)
from (SELECT Info, count(*) - 1 AS repeats
FROM Log
GROUP BY Info
HAVING repeats > 0)

MySQL SELECT query - one cell to multiple rows

In MySQL I have one particular cell with data something like this
5,6,7,8,9
If I need to search for specific 2 numbers one after another I do a query with LIKE statement for those 2 particular numbers. For ex. I need to check if there's a row with numbers 6 & 7 *in a row* I do
SELECT * FROM table WHERE column LIKE '%,6,7,%' OR column LIKE '%,6,7' OR column LIKE '6,7,%'
It's little redundant and clumsy. If I 'convert' those numbers into multiple rows, for ex. every number would become it's own row with column 'numbers' ordered with 'sort' column so I know the order of rows.
id numbers sort
55 8 4
56 6 2
57 5 1
58 7 3
59 9 5
...
What's the identical query for this case? So I would have the same result as with the query above. I need to order the query with sort column and check if the numbers 6,7 are occurring one after another with that sorting.
Should be something like this. (if I understood right your problem). It will return nothing if the 2 numbers are not in sequence by the sort column.
select *
from table t1
join table t2 on t1.sort=t2.sort+1
where t1.numbers=6 and t2.numbers=7
if you do not know which one should be first you can use it like this:
select *
from table t1
join table t2 on t1.sort=t2.sort+1 or t1.sort+1=t2.sort
where t1.numbers=6 and t2.numbers=7
Are the numbery always incremented by one or can they have any value?
I'm proposing the following table structure
id col1 col2 rowid
1 1 2 1
2 2 3 1
3 1 4 2

MySQL: Matching inexact values using "ON"

I'm way out of my league here...
I have a mapping table (table1) to assign particular values (value) to a whole number (map_nu). My second table (table2), is a collection of averages (avg) for each user (user_id).
(I couldn't figure out how to properly make a markdown table, please feel free to edit!)
table1: table2:
(value)(Map_nu) (user_id)(avg)
---- -----
1 1 1 1.111
1.045 2 2 1.2
1.09 3 3 1.33333
1.135 4 4 1
1.18 5 5 1.389
1.225 6 6 1.42
1.27 7 7 1.07
1.315 8
1.36 9
1.405 10
The value Map_nu is a special number that each user gets assigned according to their average. I need to find a way to match the averages from table2 to the closest value in table1. I only need to match to the 2 digit past the decimal, so I've added the Truncated function
SELECT table2.user_id, map_nu
FROM `table1`
JOIN table2 ON TRUNCATE(table1.value,2)=TRUNCATE(table2.avg,2)
I still miss the values that don't match the averages exactly. Is there a way to pick the nearest truncated value or even to round to the second decimal? Rounding up/down wont matter as long as its applied to all values the same.
I am trying to have the following result (if rounded up):
(user_id)(Map_nu)
----
1 4
2 6
3 6
4 1
5 10
6 11
7 3
Thanks!
i think you might have to do this in 2 separate queries. there is no 'nearest' operator in sql, so you can either calculate it in your software, or you could use
select map_nu from table1 ORDER BY abs(value - $avg) LIMIT 1
inside a loop. however, that cannot be used as a join function as it requires the ORDER and LIMIT which are not valid as joins.
another way of looking at it is it seems that your map_nu and value are deterministic in relation to each other - value = 1 + ((map_nu - 1) * 0.045) - so maybe you could make use of that fact and calculate an integer based on that equation? assuming that relationship holds true for all values of map_nu.
This is an awkward database design. What is the data representing and what are you trying to solve? There might be a better way.
Maybe do something like...
SELECT a.user_id, b.map_nu, abs(a.avg - b.value)
FROM
table2 a
join table1 b
left join table1 c on abs(a.avg - b.value) > abs(a.avg - c.value)
where c.value is null
order by a.user_id
Doesn't actually produce the same output as the one you were expecting for (doesn't do any rounding). Though you should be able to tweak it from there. Above query will produce the output below (w/ data you've provided):
user_id map_nu abs(a.avg - b.value)
------- ------ --------------------
1 3 0.0209999999999999
2 5 0.02
3 8 0.01833
4 1 0
5 10 0.016
6 10 0.0149999999999999
7 3 0.02
Beware though if you're dealing with large tables. Evaluate the explain of the above query if it'll be practical to run it within MySQL or if better to be done outside it.
Note 2: Will produce duplicate rows if there are avg values that are equi-distant to value values within table1 (Ex. if value for map_nu's 11 and 12 are 2 and 3 and someone get's an avg of 2.5). Your question doesn't really specify what to do for that so you might want to take that into account.
Its taking a little extra work, but I figure the easiest way to get my results will be to map all values to the second decimal place in table1:
1 1
1.01 1
1.02 1
1.03 1
1.04 1
1.05 2
1.06 2
1.07 2
1.08 2
1.09 3
1.1 3
1.11 3
1.12 3
1.13 3
1.14 4
...
Thanks for the suggestions! Sorry I couldn't present the question more clear.